package cn.jorian.framework.controller;

import cn.jorian.framework.bean.DataBean;
import cn.jorian.framework.bean.InboundBackBean;
import cn.jorian.framework.bean.ResponseResult;
import cn.jorian.framework.config.AppConfig;
import cn.jorian.framework.config.ConfigBean;
import cn.jorian.framework.service.*;
import cn.jorian.framework.util.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Part;
import java.io.*;

/**
 * @author jorian
 */
@RestController
@RefreshScope
public class HelloController {

    @Autowired
    private RestTemplate resttemplate;

    @Value("${config.test:22}")
    private String test;

    @Autowired
    private ConfigBean configBean;

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private IIndocBackService indocBackService;

    @Autowired
    private IOutdocBackService outdocBackService;

    @Autowired
    private IAdjustBackService iAdjustBackService;

    @Autowired
    private IOrderCancelBackService iOrderCancelBackService;

    @Autowired
    private IUploadService iUploadService;

    public HelloController(RestTemplate resttemplate) {
        this.resttemplate = resttemplate;
    }

    @RequestMapping("/hello")
    public String hello() {
        //指出服务地址   http://{服务提供者应用名名称}/{api 地址}
        String url = "http://provider-user/user/sayHello";

        //返回值类型和我们的业务返回值一致
        return resttemplate.getForObject(url, String.class);

    }

    @RequestMapping("/hi")
    public String hi() {
        //指出服务地址   http://{服务提供者应用名名称}/{api 地址}
        String url = "http://provider-user/user/sayHi";

        //返回值类型和我们的业务返回值一致
        return resttemplate.getForObject(url, String.class);

    }

    @RequestMapping("/haha")
    public String haha() {
        //指出服务地址   http://{服务提供者应用名名称}/{具体的controller}
        String url = "http://provider-user/user/sayHaha";
        //返回值类型和我们的业务返回值一致
        return resttemplate.getForObject(url, String.class);

    }

    @RequestMapping("/test")
    public String getTest() {
//        return test;
        System.out.println("日志12121");
        return configBean.getTest();
    }

    @RequestMapping("/json")
    public ResponseResult postJson() {
//        String url = "http://10.0.11.12:9080/WCSVR/functioninterface";
//        // 请求头
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
//        map.add("funcjson","{\"args\":[17L,82550L,1153L,12494821L],\"className\":\"wcsvr.svr.logic.OutStorageService\",\"funcName\":\"getSpecialDarea\",\"ifInstance\":true}");
//        HttpEntity<MultiValueMap<String,Object>> formEntity = new HttpEntity<>(map, headers);
//        String jsonObject = resttemplate.postForObject(url, formEntity, String.class);
//        System.out.println(jsonObject);
//        return jsonObject;

        //入库反馈业务单
        InboundBackBean inboundBackBean = new InboundBackBean();
        inboundBackBean.setOrderNo("121212");
        inboundBackBean.setOwnerCode("19940");



        //data
        DataBean<InboundBackBean> dataBean = new DataBean();
        dataBean.setInterfaceType("Inbound_Back");
        dataBean.setChannelType("cdfy-erp");
        dataBean.setTrackNo(inboundBackBean.getOrderNo());
        dataBean.setInterfaceNbr(UUIDUtil.getUUID());
        dataBean.addRecord(inboundBackBean);

        //appkey
        AppConfig appConfig = new AppConfig();
        appConfig.setAppKey("A827C64F23323CFF8EA186CF0757E986");
        appConfig.setAppPassword("pwd741852");

        //时间戳
        String timestamp = DateTimeUtil.getDateTime("yyyyMMddHHmmss");

        //data json
        String data = GsonUtil.toJson(dataBean);

        //data json base64编码
        String encodeData = Base64Util.encode(data);

        //签名
        String sign = MD5Util.md5Hex(timestamp + encodeData + appConfig.getAppPassword());

        //请求参数
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.add("appkey", appConfig.getAppKey());
        map.add("timestamp", timestamp);
        map.add("sign", sign);
        map.add("ver", "1");
        map.add("data", encodeData);

        //url
        String url = "http://172.16.1.73:8080/Cdfy-mawms-service-test/ma/maBack";
        //post 请求
        ResponseResult jsonObject = RestTemplateUtil.postForObject(resttemplate, url, map, ResponseResult.class);
        return jsonObject;
    }

    @RequestMapping("/goods")
    public ResponseResult goods() {
        return goodsService.goods();
    }

    @RequestMapping("/indocback")
    public ResponseResult indocback() {
        return indocBackService.indocBack();
    }

    @RequestMapping("/outdocback")
    public ResponseResult outdocback() {
        return outdocBackService.outdocBack();
    }

    @RequestMapping("/adjustback")
    public ResponseResult adjustback() {
        return iAdjustBackService.adjustBack();
    }

    @RequestMapping("/ordercancelback")
    public ResponseResult ordercancelback() {
        return iOrderCancelBackService.orderCancelBack();
    }

    @PostMapping("/image")
    public ResponseResult image(@RequestParam("funcjson") String funcjson) {
        System.out.println(funcjson);

        JSONObject jsonObject = JSON.parseObject(funcjson);

        try {
            ImageUtil.strToImage(jsonObject.getJSONArray("args").getString(4));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return ResponseResult.success();
    }

    @PostMapping("/uploadFile")
    public ResponseResult uploadFile(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) {
        System.out.println("name:" + name);
        if (file.getSize() == 0) {
            System.out.println("文件为空");
        }

        //获取文件名
        String fileName = file.getName();
        try {
            File newFile = new File("./" + fileName);
            if (!newFile.exists()) {
                newFile.createNewFile();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(newFile);
            byte[] buffer = new byte[1024];
            InputStream inputStream = file.getInputStream();
            while (inputStream.read(buffer) != -1) {
                fileOutputStream.write(buffer);
            }

            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return ResponseResult.success();
    }

    @GetMapping("/testUploadFile")
    public ResponseResult testUploadFile() {
        iUploadService.uploadFile();
        return ResponseResult.success();
    }
}
